/*
 * Rhy Animation module
 * 
 * @author Tristan Maindron
 * @dependencies rhy.core.config, rhy.core.browser
 * 
 */

Rhy.extra.anim = function (o){
    return new RhyAnimation(o);
}

Rhy.extra.easing = {
    linear: function (x) {
        return x;
    },
    
    easeInOut: function(x){
        return Math.sin(x*Math.PI/2);
    }
};

function RhyAnimation(o){
    
    this.config = {
        duration: 1000,
        from: 0,
        to: 0,
        easing: Rhy.extra.easing.linear,
        finish: function(){}
    };
    
    this.config = Rhy.config.manager.merge(this.config, o);
    this.frameInterval = 10;
    this.frame = 0;
    this.current = 0;
    this.timer = 0;

    this.frames = this.config.duration / this.frameInterval;
}			

RhyAnimation.prototype.start = function(){
    var parsed = this.parser(this.config.from, 1);
    for(var i in parsed){
        this.config.object.style[i] = parsed[i];
    }
    this.frame = 0;
    this.current = this.config.from;
    var t = this;
    this.timer = setInterval(function () {t.step(+new Date());}, this.frameInterval);
}		

RhyAnimation.prototype.pause = function(){
    clearInterval(this.timer);
}

RhyAnimation.prototype.step = function(){
    this.frame++;
    if(this.frame > this.frames){
        this.pause();
        var parsed = this.parser(this.config.to);
        for(var i in parsed){
            this.config.object.style[i] = parsed[i];
        }
        this.config.finish();
        return;
    }

    this.current = (this.config.to - this.config.from) * this.config.easing(this.frame/this.frames) + this.config.from;
    
    parsed = this.parser(this.current);
    for(var i in parsed){
        this.config.object.style[i] = parsed[i];
    }
}

RhyAnimation.prototype.parser = function(x){
    var value = [];
    if(this.config.property == 'opacity'){
        if(Rhy.browser.isFirefox()){
            value['-moz-opacity'] 	= x;
            value['opacity']        = x;
        }
        else if(Rhy.browser.isInternetExplorer()){
            if(Rhy.browser.getIExplorerVersion() >= 9){
                value['opacity']        = x;
            }
            value['filter']         = "alpha(opacity="+(100 * x)+")";
        }
        else{
            value['opacity']        = x;
        }
    }
    else{
        value[this.config.property] = x + 'px';
    }
    return value;
}
